<?php
/**
 *   Semantic Linker: Linking the semantic units in translations with their corresponding units of meaning in their manuscript sources
 *   Copyright (C) 2009  OpenScriptures.org
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @todo http://code.google.com/apis/accounts/docs/OpenID.html
 * @todo http://www.intertwingly.net/blog/2007/01/03/OpenID-for-non-SuperUsers
 * @todo http://openid.net/get/
 */

if(strpos(@$_SERVER['HTTP_ACCEPT'], 'xhtml') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false)
	header('content-type: application/xhtml+xml; charset=utf-8');
else
	header('content-type: text/html; charset=utf-8');

require_once('../inc.php');

/**
 * Load JSON encoding in case it is not natively available
 */
if(!function_exists('json_encode')){
	require_once '../JSON.php';
    function json_encode($data) {
		static $json;
		if(!isset($json))
			$json = new Services_JSON();
        return( $json->encode($data) );
    }
}


/**
 * Serve cached output, just in case we start getting lots of activity
 */
//function cacheOutput($output){
//	global $cache;
//	if(@fwrite($cache, $output)){
//		fclose($cache);
//	}
//	else {
//		$err = error_get_last();
//		$output .= "<p style='color:red'>Unable to cache output: $err[message]</p>";
//	}
//	header('ETag: "' . md5($output) . '"');
//	return $output;
//}
//if(!empty($_SERVER['QUERY_STRING'])){  //if(strpos($_SERVER['HTTP_HOST'], '-local') === false){
//	$cacheKey = substr(trim(base64_encode($_SERVER['QUERY_STRING']), '='), 0, 250);
//	if((strpos($_SERVER['HTTP_HOST'], 'local') === false) && ($cache = @file_get_contents("cache/$cacheKey.html"))){
//		$md5 = md5($cache);
//		header("ETag: \"$md5\"");
//		if(@$_SERVER['HTTP_IF_NONE_MATCH'] && strpos($_SERVER['HTTP_IF_NONE_MATCH'], $md5) !== false){
//			header('HTTP/1.1 304 Not Modified', true, 304);
//			exit;
//		}
//		print $cache;
//		exit;
//	}
//	else { //this needs to be opened here and not in the ob_start callback for some reason
//		$cache = @fopen("cache/$cacheKey.html", 'w');
//		ob_start('cacheOutput');
//	}
//}

require('../../db_config.php');
mysql_connect(DB_HOST, DB_USER, DB_PASS); //defined in db_config.php
mysql_select_db('open_scriptures');

echo '<'.'?xml version="1.0" encoding="utf-8"?'.">\n";

?>
<!DOCTYPE html><!-- XHTML5 -->
<!--
Copyright 2009, OpenScriptures.org
GPL 3 license: http://www.gnu.org/licenses/gpl.html
-->
<html xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml"><!-- xmlns:o="http://www.bibletechnologies.net/2003/OSIS/namespace"-->
	<head>
		<!--[if IE]>
		<meta charset="utf-8" />
		<script>
		//HTML5 enabling script for IE. For discussion and comments, see: http://remysharp.com/2009/01/07/html5-enabling-script/
		(function(){if(!/*@cc_on!@*/0)return;var e = "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,mark,menu,meter,nav,output,progress,section,time,video".split(','),i=e.length;while (i-=1){document.createElement(e[i])}})()
		</script>
		<![endif]-->
		<title>Semantic Linker by Open Scriptures</title>
		<!--<meta name="description" content="Allows multiple manuscripts to be compared with each other in side-by-side or unified views." />
		<meta name="keywords" content="manuscript, manuscripts, mss, comparer, comparison, compare, comparative, diff, dissimilarity, similarity, likeness, resemblance, uniformity, uniformness, parallel, unified" />-->
		<link rel="stylesheet" type="text/css" href="all.css?<?php echo filemtime('all.css') ?>" />
	</head>
	<body>
		<!--[if IE]>
		<p style="background-color:#FFCCCC; padding:1em; border:dotted 1px red; margin-left:auto; margin-right:auto; ">
			<strong>Notice:</strong> This page does not function optimally in Internet Explorer. Please try it in
			<a href="http://www.mozilla.com/firefox/">Mozilla Firefox</a>,
			<a href="http://www.apple.com/safari/">Apple Safari</a>,
			<a href="http://www.opera.com/">Opera</a>,
			or
			<a href="http://www.google.com/chrome">Google Chrome</a> <small>(administrator rights not needed to install Chrome)</small>.
		</p>
		<![endif]-->
		
		<h2><a rel="home" href="/">Open Scriptures</a></h2>
		<h1>Semantic Linker</h1>
		<noscript>
			<p><em>You should have JavaScript enabled to use this application.</em></p>
		</noscript>

		<form action="./" method="get">
			<fieldset>
			<legend>Configuration</legend>
				
			<p><label for="translation">Translation: </label><select id="translation" name="translation">
			<?php
			
			//Get all of the manuscripts in the system
			$translationQuery = mysql_unbuffered_query("SELECT id,
			                                                   url,
			                                                   (SELECT data FROM text WHERE work.name = text.id AND language = 'en') AS name,
			                                                   (SELECT data FROM text WHERE work.copyright = text.id AND language = 'en') AS copyright
			                                               FROM work
			                                               WHERE type = 'translation'");
			//Get all of the translations
			$translations = array();
			$translationsByID = array();
			while($translation = mysql_fetch_object($translationQuery)){
				$translationsByID[$translation->id] = $translation;
				$translations[] = &$translationsByID[$translation->id];
			}
			//Get all of the manuscripts that were queried for display
			$translationQueried = null;
			if(!empty($_REQUEST['translation']) && !empty($translationsByID[$_REQUEST['translation']])){
				$translationQueried = &$translationsByID[$_REQUEST['translation']];
				$translationsByID[$_REQUEST['translation']]->selected = true;
			}
			foreach($translations as &$translation){
				print "<option value='$translation->id'";
				if(!empty($translation->selected))
					print ' selected="selected"';
				print ">$translation->name</option>";
			}
			?>
			</select></p>
			<p>If desired, change the order of <b title="When multiple manuscripts agree on a reading, the displayed word is from the manuscript placed highest. Versification system of first manuscript is used." class='help'>manuscript precedence</b> based on your preference:</p>
			<ol id='mss'><?php

			//Get all of the manuscripts in the system
			$manuscriptQuery = mysql_unbuffered_query("SELECT id,
			                                                  url,
			                                                  (SELECT data FROM text WHERE work.name = text.id AND language = 'en') AS name,
			                                                  (SELECT data FROM text WHERE work.copyright = text.id AND language = 'en') AS copyright
			                                               FROM work
			                                               WHERE type = 'manuscript'");
			
			//Get all of the manuscripts
			$manuscripts = array();
			$manuscriptsByID = array();
			$manuscriptPositions = array();
			$i = 0;
			while($manuscript = mysql_fetch_object($manuscriptQuery)){
				$manuscriptPositions[$manuscript->id] = $i++;
				$manuscriptsByID[$manuscript->id] = $manuscript;
				$manuscripts[] = &$manuscriptsByID[$manuscript->id];
			}
			
			//Get the requested order of the manuscripts
			if(!empty($_REQUEST['mss']) && is_array($_REQUEST['mss'])){
				for($i = 0; $i < count($_REQUEST['mss']); $i++){
					$manuscriptPositions[$_REQUEST['mss'][$i]] = $i;
				}
				usort($manuscripts, create_function('$a,$b', 'global $manuscriptPositions; if($manuscriptPositions[$a->id] == $manuscriptPositions[$b->id]) return 0; return $manuscriptPositions[$a->id] > $manuscriptPositions[$b->id] ? 1 : -1;'));
			}
			
			$mssIDs = array();
			foreach($manuscripts as &$manuscript){
				print "<li id='li$manuscript->id'>";
				print "<input type='hidden' id='ms$manuscript->id' name='mss[]' value='$manuscript->id'";
				if(isset($manuscript->checked))
					print ' checked="checked"';
				#print "/><label for='ms$manuscript->id'> $manuscript->name</label>";
				print "/>";
				print $manuscript->name;
				print "</li>";
				$mssIDs[] = $manuscript->id;
			}
			
			?></ol>
			<p class='buttons'><button type="submit">Load</button></p>

			</fieldset>
		</form>
<?php if($translationQueried): ?>
		<hr />
		<p id="loadingNotice"><em>Loading...</em></p>

		<article id="manuscript">
		<?php
		$unifiedManuscript = mysql_fetch_object(mysql_query("SELECT workUMS.* FROM work workUMS INNER JOIN work work1 ON work1.unified_work = workUMS.id WHERE work1.id = " . $manuscripts[0]->id));
		$mssIDs_str = join(',', $mssIDs);
$tokenSQL = <<<SQL
SELECT DISTINCT
       tokenUMS.id AS tokenUMS_id,
	   tokenUMS.data AS tokenUMS_data,
       token.id AS token_id,
	   token.work AS token_work,
       token.data AS token_data,
	   token_parsing.id      AS token_parsing_id,
	   token_parsing.strongs AS token_parsing_strongs,
	   token_parsing.lemma   AS token_parsing_lemma,
	   token_parsing.parse   AS token_parsing_parse,
	   token_parsing.work    AS token_parsing_work,
	   
       ref.type AS ref_type,
       ref.numerical_start AS ref_numerical_start,
       ref_text.data AS ref_name
	   
    FROM        token AS tokenUMS
     INNER JOIN token AS token ON token.ums_token = tokenUMS.id AND token.work IN ($mssIDs_str)
	  
      LEFT JOIN token_parsing AS token_parsing ON token_parsing.token = token.id
	  
      LEFT JOIN ref ON ref.work = $mssIDs[0] AND ref.start_token = token.id
      LEFT JOIN text AS ref_text ON ref.name = ref_text.id AND language = 'en'
    WHERE tokenUMS.work = $unifiedManuscript->id
    ORDER BY tokenUMS.position ASC, ref.type ASC
SQL;
		$tokenQueryDuration = microtime(true);
		$tokenQuery = mysql_query($tokenSQL); //mysql_unbuffered_query() can't be used with mysql_data_seek()
		$tokenQueryDuration = microtime(true)-$tokenQueryDuration;

		$wordCount = 0;
		
		//Print the header, with the individual manuscript names marked up according to which set they appear in
		print "<header><h2>";
		$names = array();
		foreach($manuscripts as &$manuscript){
			$names[] = "<b id='msName$manuscript->id'>" . $manuscript->name . "</b>";
		}
		print join(' + ', $names);
		unset($names);
		
		print "</h2></header>";
		
		$tokenInfo = array();
		$display_token_data = '';
		$displayDataWorkIndex = -1;
		$works_attesting = array();
		
		$parsings = array();
		
		$inParagraph = false;
		$book = $chapter = $verse = 0;
		$bookHTML = '';
		$chapterVerseHTML = '';
		
		#mysql_data_seek($tokenQuery, 0);
		$token = mysql_fetch_object($tokenQuery);
		while($token){
			$id = 't' . $token->tokenUMS_id;
			if(!isset($tokenInfo[$id]))
				$tokenInfo[$id] = new stdClass();
			
			//Store or output the reference
			switch($token->ref_type){
				case 'book':
					if($inParagraph)
						$bookHTML = "</p><h3>$token->ref_name</h3><p>";
					else
						$bookHTML = "<h3>$token->ref_name</h3>";
					break;
				case 'chapter':
					$chapter = $token->ref_numerical_start;
					break;
				case 'verse':
					$verse = $token->ref_numerical_start;
					$chapterVerseHTML = "<sup>$chapter:$verse</sup>";
					break;
			}
			
			//Use this token as the display token if it is from a work with higher precedence
			$_displayDataWorkIndex = array_search($token->token_work, $mssIDs);
			if($displayDataWorkIndex == -1 || $_displayDataWorkIndex < $displayDataWorkIndex){
				$display_token_data = $token->token_data;
				$displayDataWorkIndex = $_displayDataWorkIndex;
			}
			$works_attesting[$token->token_work] = true;
			
			//Store parsings
			if(!empty($token->token_parsing_id)){
				$parsing = new stdClass();
				if(!empty($token->token_parsing_lemma))
					$parsing->lemma = $token->token_parsing_lemma;
				if(!empty($token->token_parsing_strongs))
					$parsing->strongs = $token->token_parsing_strongs;
				if(!empty($token->token_parsing_parse))
					$parsing->parse = $token->token_parsing_parse;
				$parsing->work = (int)$token->token_parsing_work;
				$parsings_ins[$token->token_parsing_id] = $parsing;
			}
			
			//If there is no following token or if the next token is different from this one, then print the token
			$nextToken = mysql_fetch_object($tokenQuery);
			if(!$nextToken || $token->tokenUMS_id != $nextToken->tokenUMS_id){
				$tokenInfo[$id]->u = $token->tokenUMS_data; //$umsTokens[$token->tokenUMS_id] = $token->tokenUMS_data;
				
				print $bookHTML;
				$bookHTML = ''; //reset
				if(!$inParagraph){
					print "<p>";
					$inParagraph = true;
				}
				print $chapterVerseHTML;
				
				$works_attesting_count = count($works_attesting);
				
				$elName = 'span';
				$class = '';
				
				//If all of the manuscripts in a group don't agree, then indicate and store this fact
				$allTheseAgree = ((!$works_attesting_count || $works_attesting_count == count($manuscripts)));
				if(!$allTheseAgree){
					$tokenInfo[$id]->w = array(); //$uniqueTokenWorks[$token->tokenUMS_id /*$display_token_id*/] = array();
					foreach(array_keys($works_attesting) as $workID){
						$tokenInfo[$id]->w[] = $workID; //$uniqueTokenWorks[$token->tokenUMS_id /*$display_token_id*/][] = $workID;
					}
					if($elName == 'span')
						$elName = 'b';
					$class = 'disagreed';
				}
				
				if(!empty($parsings))
					$tokenInfo[$id]->p = $parsings_del; //$tokenParsings[$token->tokenUMS_id /*$display_token_id*/] = array_values(array_merge($parsings_ins, $parsings_del));
					
				//Store the UMS token for this token
				#$umsTokenByMsToken[$token->tokenUMS_id /*$display_token_id*/] = (int)$token->tokenUMS_id;
				
				$chapterVerseHTML = ''; //reset
				print "<$elName id='t{$token->tokenUMS_id}'";
				#print " data-ums=\"" . $token->tokenUMS_data . "\"";
				if($class)
					print " class='$class'";
				print ">";
				print $display_token_data;
				#print $token_data ? $token_data : $token_del_data;
				#print $token->token_data . ':' . $token->token_del_data;
				$wordCount++;
				print "</$elName>";
				
				#if(!$allTheseAgree)
				#	print "</b>";
				print ' ';
				
				$display_token_data = ''; //reset
				$parsings = array(); //reset
				$works_attesting = array(); //reset
				$displayDataWorkIndex = -1; //reset
			}
			$token = $nextToken;
		}
		if($inParagraph)
			print "</p>";

		?>
		</article>
<?php endif; ?>
		<hr />
		<footer>
			<address>
				Copyright 2009, <a href="http://openscriptures.org/" rel="home">OpenScriptures.org</a>. 
			</address>
			<p>
				Code open source under <a href="http://www.gnu.org/licenses/gpl.html" rel="license">GPL 3</a>.
				<!--Derivative content and contributor -->Content licensed <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> if permitted by supporting works.
				<span class="host">Hosted by <a href="http://shepherd-interactive.com/">Shepherd Interactive</a>.</span>
			</p>
			<p class='repo'><?php
			$url = preg_replace('/\s+\$$/',
								'',
								preg_replace('{^.+?https://open-scriptures.googlecode.com/svn/}',
											 'http://code.google.com/p/open-scriptures/source/browse/',
											 '$URL: http://open-scriptures.googlecode.com/svn/branches/php-prototypes/semantic-linker/index.php $'));
			$basename = basename($url);
			$id = str_replace($basename,
							 "<a href='$url' title='View source code for this page'>$basename</a>",
							 '$Id: index.php 140 2009-02-13 05:44:00Z WestonRuter@gmail.com $');
			$contributorURLs = array(
				'WestonRuter@gmail.com' => 'http://weston.ruter.net/'
			);
			foreach($contributorURLs as $username => $url){
				$id = str_replace($username, "<a href='$url'>$username</a>", $id);
			}
			print preg_replace('/@\S+?(?=<|\s)/', '', $id);
			?></p>
		</footer>
	
		<?php if(file_exists('../jquery.min.js')): ?>
		<script src="../jquery.min.js?ver=1.3.1"></script>
		<?php else: ?>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
		<?php endif; ?>
		<script src="../jquery-ui-personalized-1.6rc6.min.js"></script>
		<!--<script src="../jquery.cookie.js"></script>-->
		<script src="main.js?<?php echo filemtime('main.js') ?>"></script>
		
		<!-- Google Analytics -->
		<script src="http://www.google-analytics.com/ga.js"></script>
		<script type="text/javascript">
		try {
			var pageTracker = _gat._getTracker("UA-6816157-1");
			pageTracker._trackPageview();
		} catch(e) {}
		</script>
	</body>
</html>